package com.WFinstitute.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.WFinstitute.dto.HeadImg;


public class FileLoadUtil {
	
	
	private static int sizeThreshold=4096;
	private static int maxPostSize=100 * 1024 * 1024;
	private static String savePath="/headimg/";
	private static Map<String,HeadImg> url=null;
	private static String fileName;
	@SuppressWarnings("deprecation")
	public static String  upImg(HttpServletRequest request, HttpServletResponse response,String size){
		OutputStream out = null;
		InputStream in =null;
		try {
			request.setCharacterEncoding("utf-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(sizeThreshold);
			ServletFileUpload fileUpload=new ServletFileUpload(factory);
			fileUpload.setSizeMax(maxPostSize);
			List<FileItem> lists=fileUpload.parseRequest(request);
			for (int i = 0; i < lists.size(); i++) {
				FileItem item=lists.get(i);
				if(!item.isFormField()){
				//	String fielup=item.getFieldName();
					String name=item.getName();
					String ftype=name.substring(name.lastIndexOf("."), name.length());
					System.out.println("name:"+name);
					in=item.getInputStream();
					fileName=new Date().getTime()+ftype;
					
					String path="";
					if (System.getProperty("os.name").equals("Linux")) {
							 path = request.getRealPath("/")+(savePath.substring(1))+fileName;
						  } else if (System.getProperty("os.name").indexOf("Windows")!=-1) {
							  path = request.getRealPath("/").replace("\\", "\\\\")+(savePath.substring(1)).replace("/", "\\\\")+fileName;
						  }
					if(size!=null){
						//ImageCutUtil.load(path,in, size);
						ImageCutUtil.createrImg(path,in, size);
					}else{
						out=new FileOutputStream(new File(path));
						byte[] bytes=new byte[1024];
						int leng=0;
						while((leng=in.read(bytes))!=-1){
							out.write(bytes, 0, leng);
						}
					}
					/*HeadImg img=new HeadImg();
					
					img.setName(fileName);
					img.setPath(path);
					img.setUrl(getUrlAbs(request,fileName));*/
					/*if(img == null){
						System.out.println("11111111111111111111");
					} else {
						System.out.println(img.getName()+" "+img.getPath()+" "+img.getUrl());
					}*/
					System.out.println("上传图片的名称==========="+name);
					//FileLoadUtil.url.put(name,img);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		return getUrlAbs(request,fileName);
		
	}
	
	public static InputStream readFile(HttpServletRequest request, HttpServletResponse response){
		InputStream in =null;
		try{
			request.setCharacterEncoding("utf-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(sizeThreshold);
			ServletFileUpload fileUpload=new ServletFileUpload(factory);
			fileUpload.setSizeMax(maxPostSize);
			List<FileItem> lists=fileUpload.parseRequest(request);
			for (int i = 0; i < lists.size(); i++) {
				FileItem item=lists.get(i);
				if(!item.isFormField()){
					String name=item.getName();
					String ftype=name.substring(name.lastIndexOf("."), name.length());
					in=item.getInputStream();
					return in;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return in;
		
	}
	
	
	  public static boolean downLoadFile(String filePath,
		        HttpServletResponse response, String fileName, String fileType)
		        throws Exception {
		        File file = new File(filePath);  //根据文件路径获得File文件
		        //设置文件类型(这样设置就不止是下Excel文件了，一举多得)
		        if("pdf".equals(fileType)){
		           response.setContentType("application/pdf;charset=UTF-8");
		        }else if("xls".equals(fileType)){
		           response.setContentType("application/msexcel;charset=UTF-8");
		        }else if("doc".equals(fileType)){
		           response.setContentType("application/msword;charset=UTF-8");
		        }
		        //文件名
		        response.setHeader("Content-Disposition", "attachment;filename=\""
		            + new String(fileName.getBytes(), "ISO8859-1") + "\"");
		        response.setContentLength((int) file.length());
		        byte[] buffer = new byte[4096];// 缓冲区
		        BufferedOutputStream output = null;
		        BufferedInputStream input = null;
		        try {
		          output = new BufferedOutputStream(response.getOutputStream());
		          input = new BufferedInputStream(new FileInputStream(file));
		          int n = -1;
		          //遍历，开始下载
		          while ((n = input.read(buffer, 0, 4096)) > -1) {
		             output.write(buffer, 0, n);
		          }
		          output.flush();   //不可少
		          response.flushBuffer();//不可少
		        } catch (Exception e) {
		          //异常自己捕捉       
		        } finally {
		           //关闭流，不可少
		           if (input != null)
		                input.close();
		           if (output != null)
		                output.close();
		        }
		       return false;
		    }

	
	
	public static int getSizeThreshold() {
		return sizeThreshold;
	}
	public static void setSizeThreshold(int sizeThreshold) {
		FileLoadUtil.sizeThreshold = sizeThreshold;
	}
	public static int getMaxPostSize() {
		return maxPostSize;
	}
	public static void setMaxPostSize(int maxPostSize) {
		FileLoadUtil.maxPostSize = maxPostSize;
	}
	public static String getSavePath() {
		return savePath;
	}
	public static void setSavePath(String savePath) {
		FileLoadUtil.savePath = savePath;
	}
	public static Map<String, HeadImg> getUrl() {
		return url;
	}
	public static String getFileName(){
		return fileName;
	}
	public static void setFileName(String fileName) {
		FileLoadUtil.fileName = fileName;
	}
	public static String getFileAbsPath(){
		File file1=new File("test");
		String path="";
		try {
			 path=file1.getCanonicalPath();
			 path=path.substring(0, path.lastIndexOf("\\")).replace("\\", "\\\\");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
		
	}
	
	public static String getUrlAbs(HttpServletRequest request,String fileName){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+getSavePath()+fileName;
	}
	
	public static boolean upExcel(InputStream in,Class<?> cs,List<Property> pros) throws Exception{
		if(cs!=null && pros!=null){
			try {
				Workbook book=Workbook.getWorkbook(in);
				Sheet sheet = book.getSheet(0);
				int rows = sheet.getRows();
				int cols = sheet.getColumns();
				for (int z = 1; z < rows; z++) {// 0代表列数，z代表行数?
					ObjectUtil ob=new ObjectUtil(cs);
					for (int co = 0; co < cols; co++) {
						String content = sheet.getCell(co, z).getContents();
						Property po=pros.get(co);
						Object cb=Class.forName(po.getType()).newInstance();
			            String methodname="valueOf";
			            Method method=cs.getMethod(methodname);
			            Object value= method.invoke(content);
						po.setValue(value);
						
					}
				}
				
				
			} catch (BiffException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
		
		return false;
		
	}
	
	
	
	public static void main(String[] args) {

			File file=new File("D:\\Program Files\\apache-tomcat-6.0.32\\webapps\\FEhome\\skin\\docImg\\1451045636595.png");
			System.out.println(file.exists());
			if(file.exists()){
				file.delete();
			}
			
			File file1=new File("test");
			try {
				String path=file1.getCanonicalPath();
				System.out.println(path);
			} catch (IOException e) {
				e.printStackTrace();
			}

		
	}

}
